package com.tduck.cloud.api.web.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import com.tduck.cloud.account.entity.OrgEntity;
import com.tduck.cloud.account.entity.dto.OrgEntityDTO;
import com.tduck.cloud.account.service.OrgService;
import com.tduck.cloud.api.util.UipUtils;
import com.tduck.cloud.common.constant.UipConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户异步工作
 *
 * @author Guard Baby
 * @date 2023/04/15
 */
@Slf4j
public class OrgAsyncJob implements Job {

    @Resource
    private UipUtils uipUtils;
    @Resource
    private OrgService orgService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("友空间部门同步任务开始~~~~~~~~~~~");
        String result = uipUtils.queryOrgTree(UipConstant.ROOT_ORG_ID);
        if (StringUtils.isBlank(result)) {
            return;
        }
//        log.info("result:{}", result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        List<OrgEntityDTO> orgEntityList = Lists.newArrayList();
        if (UipConstant.SUCCESS_CODE.equals(code)) {
            JSONArray data = jsonResult.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject d = data.getJSONObject(i);
                OrgEntityDTO orgEntity = JSONObject.parseObject(data.getString(i), OrgEntityDTO.class);
                orgEntityList.add(orgEntity);
            }
        }
        List<OrgEntity> orgEntities = expandTreeData(orgEntityList, Lists.newArrayList());
        if (CollUtil.isNotEmpty(orgEntities)){
            log.info("共获取到数据{}条",orgEntities.size());
            //保存或更新ac_org表
            orgService.saveOrUpdateBatch(orgEntities);
        }
        log.info("^^^^^^^^^^^^^友空间部门同步任务结束^^^^^^^^^^");


    }

    private List<OrgEntity> expandTreeData(List<OrgEntityDTO> orgEntityList, List<OrgEntity> allList) {
        if (CollUtil.isEmpty(orgEntityList)) {
            return null;
        }
        for (int i = 0; i < orgEntityList.size(); i++) {
            OrgEntityDTO dto = orgEntityList.get(i);
            allList.add(BeanUtil.toBean(dto, OrgEntity.class));
            if (CollUtil.isNotEmpty(dto.getChildren())) {
                expandTreeData(dto.getChildren(), allList);
            }
        }
        return allList;
    }


}
